//
//  MYGUploadManager.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/3.
//

import UIKit
import Alamofire
import Moya
import HandyJSON

class MYGUploadModel:NSObject, HandyJSON, NSSecureCoding ,Decodable,NSCoding {
    static var supportsSecureCoding: Bool {
        return true
    }
    
    
//    enum CodingKeys: String, CodingKey {
//        case status = "status"
//        case name = "name"
//        case progress = "progress"
//        case url = "url"
//        case file_type = "file_type"
//        case f_id = "f_id"
//    }
// 
    var name = ""
    var status = ""//0:上传中，1：已上传
    var progress = ""
    var url = ""
    var file_type = ""//（1 图片 2视频 3文档）
    var f_id = "" //文件夹id,0放到最外层
    func encode(with coder: NSCoder) {
        coder.encode(status, forKey: "status")
        coder.encode(name, forKey: "name")
        coder.encode(progress, forKey: "progress")
        coder.encode(file_type, forKey: "file_type")

        coder.encode(url, forKey: "url")
        coder.encode(f_id, forKey: "f_id")
    }
    required override init() {
        super.init()
    }
    required init?(coder: NSCoder) {
        super.init()
        progress = coder.decodeObject(forKey: "progress") as? String ?? ""
        name = coder.decodeObject(forKey: "name") as? String ?? ""
        file_type = coder.decodeObject(forKey: "file_type") as? String ?? ""
        url = coder.decodeObject(forKey: "url") as? String ?? ""
        status = coder.decodeObject(forKey: "status") as? String ?? ""
        f_id = coder.decodeObject(forKey: "f_id") as? String ?? ""

    }
}

class MYGUploadManager: NSObject {
    private let fileManeger = FileManager.default
    private let mainPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last ?? ""
    
    static let shared = MYGUploadManager()
    var uploadingArray = [MYGUploadModel]()//上传中
    var uploadedArray = [MYGUploadModel]()//上传完成
    
    func getCacheData() {
        guard let models = MYGUploadManager.shared.getDownloadModels() else {return}
        MYGUploadManager.shared.uploadedArray = models
    }

    
    enum FileUploadType: Error {
        case image
        case video
        case file
    }
    
    let workingGroup = DispatchGroup()
    let workingQueue = DispatchQueue(label: "request_queue")
    
    func addUploadTask(fileData:Data,fileName:String,type:FileUploadType,fid:Int) {
        workingGroup.enter()
        workingQueue.async {[weak self] in
            self?.requestUploadTask(fileData: fileData, fileName: fileName, type: type, fid: fid, completion: {
                self?.workingGroup.leave()
            })
        }
    }
    
    func requestUploadTask(fileData:Data,fileName:String,type:FileUploadType,fid:Int,completion:@escaping (()->())) {
        var uploadType = ""
        let model = MYGUploadModel()
        model.name = fileName
        model.f_id = "\(fid)"
        
        if type == .image {
            model.file_type = "1"
            uploadType = "image/*"
        }
        if type == .video {
            model.file_type = "2"
            uploadType = "audio/*"
        }
        if type == .file {
            model.file_type = "3"
            uploadType = "audio/*"
        }
        
        MYGUploadManager.shared.uploadingArray.append(model)
        DispatchQueue.main.async {
            NotificationCenter.default.post(name: Notification.Name("MYGCloudDiskUploadManager_addUploadTask"), object: nil)
            NotificationCenter.default.post(name: Notification.Name("MYCloudDiskHeaderActionView_reloadRedLB"), object: nil)
        }
        MYGNetwork<MYGCommonAPI, MYGEmptyModel>.upload(target: .uploadOssFiles(image: nil,data: fileData,fileName: fileName, type: uploadType),progressCallBack: { progress in
            print("progress=\(progress)")
            model.progress = "\(progress)"
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: Notification.Name("MYGCloudDiskUploadManager_progress"), object: model)
            }
        }) {[weak self] url in
            model.url = url
            model.status = "1"
            self?.connectToCloudDisk(model: model)
            self?.updateUploadModel(model) {
                self?.saveModels(model)//缓存上传完成的
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: Notification.Name("MYCloudDiskHeaderActionView_reloadRedLB"), object: nil)
                    NotificationCenter.default.post(name: Notification.Name("MYGCloudDiskUploadManager_uploadStatusChanged"), object: model)
                }
            }
            completion()
        } failed: { _, error in
            completion()
            MYGLoading.hide()
        }
    }
    //上传中->上传完成
    func updateUploadModel(_ model:MYGUploadModel,completion:@escaping (()->())) {
        MYGUploadManager.shared.uploadingArray = MYGUploadManager.shared.uploadingArray.filter({ obj in
            return obj.name != model.name
        })
        let result = MYGUploadManager.shared.uploadingArray.filter { obj in
            return obj.name == model.name
        }
        if result.count == 0 {
            MYGUploadManager.shared.uploadedArray.append(model)
        }
        completion()
    }
    
    //上传完成后与云盘关联
    func connectToCloudDisk(model:MYGUploadModel) {
        let parms = ["name":model.name,"type":"1","f_id":"\(model.f_id)","url":model.url,"state":"1","file_type":model.file_type]
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .netdiskLogAdd(param: parms)) { result in
            NotificationCenter.default.post(name: Notification.Name("MYCloudDiskViewController_configDataSource"), object: nil)

        } failed: { _, error in
            MYGLoading.hide()
        }
    }
    func writeDataToFilePath(with filePath:String ,fileData:Data?) -> Bool{
        
        return fileManeger.createFile(atPath: filePath, contents: fileData, attributes: nil)
    }
   
}

class ICouldManager {
    public static func iCouldEnable() -> Bool {
        let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)
        return (url != nil)
    }
    
    public static func downloadFile(WithDocumentUrl url: URL, completion: ((Data) -> Void)? = nil) {
        let document = SxsDocument.init(fileURL: url)
        document.open { (success) in
            if success {
                document.close(completionHandler: nil)
            }
            if let callback = completion {
                callback(document.data)
            }
        }
    }
}

class SxsDocument: UIDocument {
    public var data = Data.init()
    
    override func load(fromContents contents: Any, ofType typeName: String?) throws {
        if let d = contents as? Data {
            self.data = d
        }
    }
}
